package com.yjt.javatest.service.impl;

import com.yjt.javatest.service.LatexService;
import org.scilab.forge.jlatexmath.TeXConstants;
import org.scilab.forge.jlatexmath.TeXFormula;
import org.scilab.forge.jlatexmath.TeXIcon;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@Service
public class LatexServiceImpl implements LatexService {
    public static BufferedImage renderEquation(String latexString) {
        TeXFormula formula = new TeXFormula(latexString);
        TeXIcon icon = formula.createTeXIcon(TeXConstants.STYLE_DISPLAY, 20);
        BufferedImage image = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = image.createGraphics();
        g2.setColor(Color.white);
        g2.fillRect(0, 0, icon.getIconWidth(), icon.getIconHeight());
        JLabel label = new JLabel();
        label.setForeground(Color.black);
        icon.paintIcon(label, g2, 0, 0);
        g2.dispose();
        return image;
    }
    @Override
    public byte[] latexToPng(String latexString) throws IOException{
        BufferedImage image = renderEquation(latexString);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        byte[] imageBytes = baos.toByteArray();
        return imageBytes;
    }
}
